package org.example.big_data.controller;

import org.example.big_data.pojo.Article;
import org.example.big_data.pojo.PageBean;
import org.example.big_data.pojo.Result;
import org.example.big_data.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    //  1 新增文章内容
    @PostMapping
    public Result add(@RequestBody @Validated Article article) {
        articleService.add(article);
        return Result.success("成功了老弟！");
    }

    // 2 文章分页查询，最复杂！需要额外的实体类来封装返回的data中的个数据

    /**
     * 文章分页查询
     * @param pageNum   请求的哪一页页码，必要参数，应用@RequestParam(defaultValue = "1")注解设置默认值
     * @param pageSize  每页显示几条数据，必要参数，应用@RequestParam(defaultValue = "10")注解设置默认值
     * @param categoryId   分类id，前端搜索功能时使用，非必要参数，应用@RequestParam(required = false)注解标识
     * @param state   文章状态，前端搜索功能时使用，非必要参数，应用@RequestParam(required = false)注解标识
     * @return
     */
    @GetMapping
    public Result<PageBean<Article>> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize,
                                          @RequestParam(required = false) Integer categoryId,
                                          @RequestParam(required = false) String state) {
        PageBean<Article> pageBean = articleService.list(pageNum, pageSize, categoryId, state);
        return Result.success(pageBean);  //pagebean类型的返回值作为Result的data
    }

    //3 /article/detail根据id查询文章详情，即返回文章对象
    @GetMapping("/detail")
    public Result<Article> detail(@RequestParam Integer id){
        Article article = articleService.detail(id);
        //如果文章不存在，返回错误信息
        if (article == null) {
            return Result.error("文章不存在");
        }
        return Result.success(article);
    }

    //4 根据id更新文章
    @PutMapping
    public Result update(@RequestBody Article article){
        if (article.getId() == null) {
            return Result.error("文章id不能为空");
        }
        articleService.update(article);
        return Result.success("更改成功");
    }

    //5 根据id删除文章
    @DeleteMapping
    public Result delete(@RequestParam Integer id){
        if (id == null) {
            return Result.error("文章id不能为空");
        }
        articleService.delete(id);
        return Result.success("成功");
    }

}
